package com.wyg.blog.service.serviceimpl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wyg.blog.mapper.UserMapper;
import com.wyg.blog.model.user.User;
import com.wyg.blog.service.user.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * @description:
 * @author: WYG
 * @time: 2020/6/21 21:20
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserMapper userMapper;

    @Override
    public User selectUserByUsername(String username) {
        return userMapper.getUserByName(username);
    }

    @Override
    public IPage<User> selectUsers(Page<?> page) {
        return userMapper.getUsers(page);
    }

    @Override
    public Integer selectUserNum(String username) {
        return userMapper.getUserNum(username);
    }

    @Override
    public Integer insertUser(User user) {
        boolean res =  userMapper.addUser(user);
        return user.getId();
    }

    @Override
    public boolean checkLogin(String username, String password) throws Exception {
        User user = userMapper.getUserByName(username);
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        if(user == null) {
            throw new Exception("账号不存在，请检查");
        } else {
            String encoderPassword = user.getPassword();
            if(!bCryptPasswordEncoder.matches(password, encoderPassword)){
                throw new Exception("密码不正确");
            }else {
                return true;
            }
        }
    }

    @Override
    public boolean renewPwd(String username, String password) {
        return userMapper.updatePwd(username,password);
    }

    @Override
    public boolean activate(String username) {
        return userMapper.activateUser(username);
    }

    @Override
    public boolean removeUser(String username) {
        return userMapper.deleteUser(username);
    }
}
